package com.atao.baokede.controller;

import com.atao.baokede.pojo.Result;
import com.atao.baokede.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 图片上传层
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;
    /**
     * 图片上传
     * @param file 图片文件
     * @return 图片上传地址
     */
    @PostMapping("/photoUpload")
    public Result uploadPhoto(MultipartFile file) throws Exception {
        // 1. 校验文件类型
        if (file == null || file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        if (!ALLOWED_CONTENT_TYPES.contains(file.getContentType())) {
            return Result.error("文件类型不支持，仅允许上传常见格式图片");
        }

        String url = fileService.uploadPhoto(file);

        // 6. 返回上传图片地址
        return Result.success(url);
    }


/*    *//**
     * 阿里云图片删除
     * @param url 图片地址
     * @return 删除结果
     *//*
    @DeleteMapping("/photoDelete")
    public Result deletePhoto(@RequestParam String url){
        // 截取从 "oss-cn-hangzhou.aliyuncs.com/" 之后的部分
        String fileName = url.substring(url.indexOf("oss-cn-hangzhou.aliyuncs.com/") + "oss-cn-hangzhou.aliyuncs.com/".length());
        // 删除文件
        AliOssUtil.deleteFile(fileName);
        return Result.success();
    }*/

    /**
     * minio图片删除
     * @param url 图片地址
     * @return 删除结果
     */
    @DeleteMapping("/photoDelete")
    public Result deletePhoto(@RequestParam String url) throws Exception {
        fileService.deletePhoto(url);
        return Result.success();
    }


    /**
     * 允许的图片类型
     */
    private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
            "image/jpeg",
            "image/png",
            "image/webp"
    );
}